package com.yipin.neimeng.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class SecurityUtils {

    /**
     * 使用AES算法解密16进制字符串
     *
     * @param encryptedHex 待解密的16进制字符串
     * @param key          解密密钥
     * @return 解密后的字符串
     */
    public static String decodeAES256HexUpper(String encryptedHex, String key) {
        try {
            if (key.length() < 32) {
                throw new IllegalArgumentException("密钥长度必须是32个字符");
            }
            if (encryptedHex.length() % 2 != 0) {
                throw new IllegalArgumentException("Encrypted hex string has an invalid length.");
            }

            byte[] keyBytes = new byte[32];
            byte[] encryptedBytes = new byte[encryptedHex.length() / 2];

            // Fill keyBytes with the key string bytes
            System.arraycopy(key.getBytes(StandardCharsets.UTF_8), 0, keyBytes, 0, keyBytes.length);

            // Convert the encrypted hex string to bytes
            for (int i = 0; i < encryptedBytes.length; i++) {
                int index = i * 2;
                int high = Character.digit(encryptedHex.charAt(index), 16);
                int low = Character.digit(encryptedHex.charAt(index + 1), 16);
                if (high == -1 || low == -1) {
                    throw new IllegalArgumentException("Invalid hex string");
                }
                encryptedBytes[i] = (byte) (high << 4 | low);
            }

            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 使用公钥解密数据
     *
     * @param encryptedData 待解密的字符串
     * @param publicKeyStr  公钥字符串
     * @return 解密后的字符串
     */
    public static String decryptByPublicKey(String encryptedData, String publicKeyStr) {
        try {
            byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyStr);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将十六进制字符串解码为字节数组。
     *
     * @param hexString 十六进制字符串
     * @return 解码后的字节数组
     */
    public static String decodeHexUpper(String hexString) {
        if (hexString == null) {
            return null;
        }
        if (hexString.length() % 2 != 0) {
            throw new IllegalArgumentException("Invalid hexadecimal string: length must be even");
        }

        char[] hexChars = hexString.toCharArray();
        byte[] bytes = new byte[hexChars.length / 2];

        for (int i = 0; i < hexChars.length; i += 2) {
            int byteValue = (Character.digit(hexChars[i], 16) << 4) | Character.digit(hexChars[i + 1], 16);
            bytes[i / 2] = (byte) byteValue;
        }

        return bytes.toString();
    }
}
